<?php

namespace App\Models\Traits;

use App\Models\ChatUserModel;
use App\Util\AdminLogUtil;
use Illuminate\Database\Eloquent\Model;

trait HasModelLog
{
    protected static function bootHasModelLog()
    {


        if (app()->runningInConsole()) return true;
//        if (get_called_class() === \App\Models\AdminLogModel::class) return true;

        static::created(function(Model $model){
            try{
                AdminLogUtil::created($model->getTable(),$model->getAttributes());
            }catch (\Exception $e){

            }
        });

        static::updating(function(Model $model){

            if(!empty($model->getOriginal())){
                return ;
            }

            try{
                //没有数据先获取数据
                $id = data_get($model,$model->getKeyName());
                if(!empty($id)){
                    $sources = $model->newQuery()->find($id);
                    $data = $model->getAttributes();
                    $model->setRawAttributes($sources->getAttributes(),true);
//                    foreach ($data as $key=> $v){
//                        $model->setAttribute($key,data_get($sources,$key));
//                    }
//                    $model->syncOriginal();
                    $model->setRawAttributes($data);
                }

            }catch (\Exception $e){

            }
        });
//        static::updated(function(Model $model) {
//            try{
//
//                AdminLogUtil::updated($model->getTable(),$model->getOriginal(),$model->getAttributes());
//            }catch (\Exception $e){
//
//            }
//        });
        static::deleted(function(Model $model){
            try{
                AdminLogUtil::deleted($model->getTable(),$model->getOriginal());
            }catch (\Exception $e){

            }
        });


    }

    public function modelLogs()
    {
//        return $this->morphMany(ChatUserModel::class, 'id');
    }
}
